package com.cskaoyan.service;

import com.cskaoyan.bean.BaseParam;
import com.cskaoyan.bean.user.Collect;
import com.cskaoyan.bean.user.CollectExample;
import com.cskaoyan.bean.BaseData;
import com.cskaoyan.bean.wxcollect.CollectInfo;
import com.cskaoyan.bean.wxcollect.CollectParam;
import com.cskaoyan.bean.wxcollect.bo.AddordeleteBO;
import com.cskaoyan.mapper.CollectMapper;
import com.cskaoyan.util.DateUtils;
import com.cskaoyan.util.PageUtil;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * \* Description:
 * \
 */
@Service
public class CollectServiceImpl implements CollectService {

    @Autowired
    CollectMapper collectMapper;

    @SuppressWarnings("all")
    @Override
    public BaseData<Collect> address(BaseParam param, Integer userId, Integer valueld) {
        PageUtil.start(param);

        CollectExample collectExample = new CollectExample();
        collectExample.setOrderByClause(param.getSort() + " " + param.getOrder());
        CollectExample.Criteria criteria = collectExample.createCriteria();
        if (userId != null && !"".equals(userId))
            criteria.andUserIdEqualTo(userId);
        if (valueld != null && !"".equals(valueld))
            criteria.andValueIdEqualTo(valueld);
        List<Collect> collectList = collectMapper.selectByExample(collectExample);
        PageInfo<Collect> collectPageInfo = new PageInfo<>(collectList);
        BaseData<Collect> collectBaseData = new BaseData<>(collectPageInfo, collectList);
        return collectBaseData;
    }

    @Override
    public BaseData<CollectInfo> list(CollectParam param) {
        PageUtil.start(param);
        List<CollectInfo> collectInfos = collectMapper.getCollectInfo();
        PageInfo<CollectInfo> pageInfo = new PageInfo<>(collectInfos);
        BaseData<CollectInfo> data = new BaseData<>(pageInfo, collectInfos);
        return data;
    }

    @Override
    public int addordelete(AddordeleteBO bo) {
        Integer type = bo.getType();
        Integer valueId = bo.getValueId();
        String time = DateUtils.dateFormat(new Date());
        int num = 0;
        //先根据value_id 判断是否收藏，若未收藏，则执行addCollect，
        // 已收藏执行deleteCollect，逻辑删除，将deleted修改为1
        List<Integer> valueIdList = collectMapper.selectValueIdByDeleted();
        for (Integer id : valueIdList) {
            if (valueId.equals(id)) {
                //如果已经收藏就将deleted修改为1，并且更新修改时间
                num = collectMapper.updateDeleted(valueId, time);
                break;
            }
        }
        if (num == 0) {
            num = collectMapper.addCollect(type, valueId, time);
        }

        return num;
    }
}

